import React, { useEffect, useRef, useState } from 'react'
import { NavBar, Form, Input, Button, ImageUploader, VirtualInput, NumberKeyboard, Radio, Cascader, Toast } from 'antd-mobile'
import './User.css'
import { PictureOutline } from 'antd-mobile-icons'
import options  from './option'
import ajax from '../../api/ajax'

import { useDispatch, useSelector } from 'react-redux';
import { userChange } from '../../redux/UserSlice/UserSlice';
import { useNavigate } from 'react-router-dom'

export default function User() {
    const navigate = useNavigate()
    const back = () => {
        window.history.back(-1)
    }
    const dispatch = useDispatch();
    let user = useSelector(state => state.UserSliceReducer.user)
    // 获取用户信息
    useEffect(()=>{
        let x = JSON.parse(localStorage.getItem('userToken')) 
        if(x==null) return 
        dispatch(userChange(x))
    },[])
    useEffect(()=>{
        setImgAddress(user.imgurl)
    })
    // 图片上传
    const [imgAddress,setImgAddress]=useState('')
    const [fileList, setFileList] = useState([
        {
            url: user.imgurl,
        },
    ])
    function mockUpload(file) {
        
        return {
            url: URL.createObjectURL(file),
        }
    }

    // 电话
    const [AuthCodeShow, setAuthCodeShow] = useState(false)
    const phoneChange = (value) => {
        if (value != user.tel) {
            setAuthCodeShow(true)
        } else {
            setAuthCodeShow(false)
        }
    }
    // 验证码
    // 发送验证码
    const [getCodeText, setGetCodeText] = useState(false)
    let [time, setTime] = useState(10)
    let timer  //节流

    let [autoCodeJudge, setAutoCodeJudge] = useState('-10086')
    const getUserAutoCode = async () => {
        const values = form.getFieldValue()
        const newPhone = values.tel
        const phoneReg = /^[1][3|4|5|7|8|9][0-9]{9}$/
        if (!phoneReg.test(newPhone)) {
            Toast.show({
                content: '请输入正确的手机号',
            })
            return;
        } else {
            if (timer) {
                return ;
                // 节流作用
            }
            timer = setInterval(() => {
                // 发送请求
                setGetCodeText(true)
                setTime(time--)

                if (time <= -2) {
                    // console.log('time<0', time <= 0);
                    clearInterval(timer)
                    setGetCodeText(false)
                    setTime(10)
                }
            }, 1000)

            const result = await ajax.post('/account/sendCode', {
                tel: values.tel,
            })
            console.log('result.data',result.data);
            setAutoCodeJudge(result.data)
        }

    }

    // 城市
    const [visible, setVisible] = useState(false)
    const [city, setCity] = useState(user.city)
    const cityConfirm = (value) => {
        setCity(value.join('-'))
    }

    // 表单提交
    const [form] = Form.useForm()
    const formSubmit = async () => {
        let id = JSON.parse(localStorage.getItem('userToken')).id
        let oldTel = JSON.parse(localStorage.getItem('userToken')).tel
        const values = form.getFieldValue()
        let telChange = false
        if (oldTel != values.tel) {
            telChange = true
        }
        
        if (telChange){
            if (autoCodeJudge === '') {
                Toast.show({
                    icon: 'fail',
                    content: '未发送验证码',
                })
                return;
            } else if (autoCodeJudge !== values.AutoCode) {
                // 比较验证码是否匹配
                Toast.show({
                    icon: 'fail',
                    content: '验证码不匹配',
                })
                return;
            }
        }
/*         else if (values.AutoCode !== '') {
            // console.log('更新电话', values.tel);
            const result2 = await ajax.post('/account/updateTel', {
                newTel: values.tel
            })
        } */

        let newValues

        
        
        // console.log('values---', values);
        if (values.img){
            // // 将blod转化为base64
            // const blob = values.img[0].url
            // const image = new Image()
            // image.src = blob;
            // image.onload = () => {
            //     const canvas = document.createElement('canvas')
            //     let imgUrl = canvas.toDataURL() //图片的base64地址
            //     values.img[0].url = imgUrl
            // }
            
            // 如果更改了图片
            console.log('图片已改变');
            values.imgurl = values.img[0].url
            delete values['img']
            
        }else{
            console.log('未改变图片');
        }
        setImgAddress(values.imgurl)

        newValues = { 
            ...values, 
            city,
            id,
            AutoCode:''
        }

        
        // 发送保存用户数据都请求
        const result = await ajax.post('/user/updateUser', { ...newValues, telChange, oldTel })
        if (result.msg == '此电话账号已存在'){
            Toast.show({
                icon: 'fail',
                content: <center>
                    更新失败,<br />此电话已存在
                </center>,
            })
            return ;
        }else if (result.msg =='TelSuccess'){
            // 框内验证码置为空
            Toast.show({
                icon: 'success',
                content: <center>
                    更新成功,<br />重新登录,<br />5s后自动退出!
                </center>,
            })
            setTimeout(() => {
                localStorage.removeItem('Authorization')
                localStorage.removeItem('persist:root')
                localStorage.removeItem('userToken')
                navigate('/')
            }, 5000);
            return;
        } else if (result.msg == 'MsgSuccess'){
            Toast.show({
                icon: 'success',
                content: <center>
                    未更改电话,<br />其它信息更新成功
                </center>,
            })
        }
        dispatch(userChange(newValues))
        localStorage.setItem('userToken', JSON.stringify(newValues))
        
    }



    return (
        <div className='User'>
            <NavBar onBack={back} className='UserTop'>账户</NavBar>
            <Form layout='horizontal' mode='card' form={form}
                footer={
                    <Button block size='large' type='submit' onClick={formSubmit} className='UserButoon'>
                        保存
                    </Button>
                }
                onFinish={formSubmit}
                className='Form'
                // 初始化数据
                initialValues={user}
            >
                <Form.Item label='头像' name='img'>
                    <ImageUploader value={fileList} defaultValue={fileList} onChange={setFileList} upload={mockUpload}
                        maxCount={1} className='pitcture'>
                        <div
                            style={{
                                width: 80,
                                height: 80,
                                borderRadius: 40,
                                backgroundColor: '#f5f5f5',
                                display: 'flex',
                                justifyContent: 'center',
                                alignItems: 'center',
                                color: '#999999',
                            }}
                        >
                            <PictureOutline style={{ fontSize: 32 }} />
                        </div>
                    </ImageUploader>
                </Form.Item>
                <Form.Item label='手机号' name='tel'>
                    <VirtualInput
                        placeholder='...'
                        keyboard={<NumberKeyboard
                            confirmText='确定' />}
                        style={{ '--caret-width': '1px', '--caret-color': '#666666' }}
                        onChange={phoneChange} />
                </Form.Item>
                {AuthCodeShow ? <Form.Item
                    label='验证码'
                    extra={
                        <div className='extraPart'>
                            {
                                getCodeText ? <span className='userGetAutoCode'>
                                    {time + 's'}</span>
                                    :
                                    <a onClick={() => getUserAutoCode()}>发送验证码</a>
                            }
                        </div>
                    }
                    name='AutoCode'
                    className='AuthCode'
                >
                    <Input placeholder='...' clearable  />
                </Form.Item> : null}

                <Form.Item label='姓名' name='name'>
                    <Input placeholder='...' />
                </Form.Item>
                <Form.Item label='性别' name='sex'>
                    <Radio.Group>
                        <Radio value='男'>男</Radio> &nbsp;
                        <Radio value='女'>女</Radio>
                    </Radio.Group>
                </Form.Item>
                <Form.Item label='城市' name='city' className='city'>
                    <Button
                        onClick={() => {
                            setVisible(true)
                        }}
                    >
                        {city}
                    </Button>
                    <Cascader
                        options={options }
                        visible={visible}
                        onClose={() => {
                            setVisible(false)
                        }}
                        onConfirm={cityConfirm}
                    />
                </Form.Item>


            </Form>
        </div>
    )
}
